package cn.zzq.shop.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.nio.file.Path;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;

@Component("ftpUtil")
public class FtpUtil
{
	/*ip*/
	private String ip = ConstatFinalUtil.CONFIG_JSON.getString("ftp.ip");
	/*port*/
	private int port = Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.getString("ftp.port")+"");
	/*username*/
	private String username = ConstatFinalUtil.CONFIG_JSON.getString("ftp.username");
	/*password*/
	private String password = ConstatFinalUtil.CONFIG_JSON.getString("ftp.password");
	/*ftp客户端*/
	private FTPClient client;
	
	/*登录FTP*/
	private boolean login(){
		ConstatFinalUtil.SYS_LOGGER.info("-----login----");
		/*创建一个客户端*/
		client = new FTPClient();
		boolean flag = false;
		
		try
		{
			/*连接*/
			client.connect(ip,port);
			/*登录*/
			flag = client.login(username,password);
		} catch (Exception e)
		{
			/*报错信息*/
			ConstatFinalUtil.SYS_LOGGER.error("登录FTP报错了");
		}
		return flag;
	}
	
	/*上传文件*/
	public boolean uploadFile(String fileName,String path,InputStream is){
		/*判断是否登录*/
		if(!this.login()){
			ConstatFinalUtil.SYS_LOGGER.error("---登录失败---");
			return false;
		}
		
		try
		{
			/*进入根目录*/
			client.cwd("/");
			/*把\换成/*/
			path = path.replaceAll("\\\\", "/");
			/*相对路径分离出数组*/
			String[] paths = path.split("/");
			/*循环数组，创建父子目录*/
			for(int i = 0;i < paths.length; i++){
				String pathTemp = paths[i];
				/*创建目录*/
				if(!client.makeDirectory(pathTemp)){
					ConstatFinalUtil.SYS_LOGGER.error("--创建目录失败--");
				}
				/*进入到刚创建的目录*/
				client.cwd(pathTemp);
			}
			
			/*上传文件*/
			return client.storeFile(fileName, is);
		} catch (IOException e)
		{
			/*报错信息*/
			ConstatFinalUtil.SYS_LOGGER.error("上传文件报错,fileName{}",fileName,e);
		}
		
		return false;
	}
	
}
